﻿using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using OpenReflect.Domain.Contracts;
using OpenReflect.Domain.Model;

namespace OpenReflect.Services.Builders
{
	public interface IParameterBuilder
	{
		IList<IParameter> CreateParameters(MethodDefinition definition);
		IParameter CreateParameter(ParameterDefinition definition);
	}

	public class ParameterBuilder : IParameterBuilder
	{
		#region IParameterBuilder Members

		public IList<IParameter> CreateParameters(MethodDefinition definition)
		{
			var parameterList = new List<IParameter>(definition.Parameters.Capacity);
			foreach (ParameterDefinition parameterDefinition in definition.Parameters)
			{
				IParameter param = CreateParameter(parameterDefinition);
				parameterList.Add(param);
			}
			return parameterList;
		}

		public IParameter CreateParameter(ParameterDefinition definition)
		{	
			var typeBuilder = new TypeDeclarationBuilder();
			IParameter retVal = new Parameter();
			retVal.Name = definition.Name;
			var assemblyResolver = new AssemblyResolver();
			var typeDefinition = assemblyResolver.Resolve(definition.ParameterType);
			retVal.TypeDeclaration = typeBuilder.CreateTypeDeclaration(typeDefinition);

			//TODO: a global dictionary somewhere can be used to map System.Type->TypeDefinition
			return retVal;
		}

		#endregion
	}
}